<template>
  <div class="contract-audit">
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <el-form-item label="合同编号">
          <el-input 
            v-model="searchForm.contractNo" 
            placeholder="请输入合同编号" 
            clearable 
            style="width: 180px;"
          />
        </el-form-item>
        
        <el-form-item label="审核状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择审核状态" 
            clearable 
            style="width: 150px;"
          >
            <el-option label="待审核" value="待审核" />
            <el-option label="审核通过" value="审核通过" />
            <el-option label="审核拒绝" value="审核拒绝" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="客户代码">
          <el-input 
            v-model="searchForm.customerCode" 
            placeholder="请输入客户代码" 
            clearable 
            style="width: 150px;"
          />
        </el-form-item>
        
        <el-form-item label="客户名称">
          <el-input 
            v-model="searchForm.customerName" 
            placeholder="请输入客户名称" 
            clearable 
            style="width: 180px;"
          />
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-input 
            v-model="searchForm.salesperson" 
            placeholder="请输入业务员" 
            clearable 
            style="width: 150px;"
          />
        </el-form-item>
        
        <el-form-item label="审核人">
          <el-input 
            v-model="searchForm.auditBy" 
            placeholder="请输入审核人" 
            clearable 
            style="width: 150px;"
          />
        </el-form-item>
        
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px;"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 合同列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>合同列表</span>
          <div class="header-actions">
            <el-button @click="handleRefresh" :icon="Refresh" circle />
          </div>
        </div>
      </template>

      <el-table 
        :data="contractList" 
        v-loading="loading" 
        border 
        stripe 
        class="contract-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="contractNo" label="合同编号" width="150" />
        <el-table-column label="报价单号" width="150">
          <template #default="scope">
            {{ scope.row.quotation?.quotationNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="客户代码" width="120">
          <template #default="scope">
            {{ scope.row.quotation?.customerCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" width="180">
          <template #default="scope">
            {{ scope.row.quotation?.customerName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="业务员" width="100">
          <template #default="scope">
            {{ scope.row.quotation?.salesperson || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="合同金额" width="120" align="right">
          <template #default="scope">
            <span class="amount-text">¥{{ formatAmount(scope.row.quotation?.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditBy" label="审核人" width="100" />
        <el-table-column prop="auditTime" label="审核时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.auditTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewDetail(scope.row)"
              :icon="View"
            >
              查看
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handlePreview(scope.row)"
              :icon="Document"
            >
              预览合同
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handleDownload(scope.row)"
              :icon="Download"
            >
              下载合同PDF
            </el-button>
            <el-button 
              v-if="canAudit(scope.row)"
              type="warning" 
              size="small" 
              @click="handleAudit(scope.row)"
              :icon="Edit"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 合同详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="合同详情" 
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="currentContract" class="contract-detail">
        <!-- 基本信息 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">基本信息</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>合同编号：</label>
                <span>{{ currentContract.contractNo }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>报价单号：</label>
                <span>{{ currentContract.quotation?.quotationNo || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>审核状态：</label>
                <el-tag :type="getStatusTagType(currentContract.status)">
                  {{ currentContract.status }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>客户代码：</label>
                <span>{{ currentContract.quotation?.customerCode || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>客户名称：</label>
                <span>{{ currentContract.quotation?.customerName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>业务员：</label>
                <span>{{ currentContract.quotation?.salesperson || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>合同金额：</label>
                <span class="amount-text">¥{{ formatAmount(currentContract.quotation?.totalAmount) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>付款方式：</label>
                <span>{{ currentContract.quotation?.paymentMethod || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>是否含税：</label>
                <span>{{ currentContract.quotation?.isTaxIncluded ? '是（13%）' : '否' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>创建时间：</label>
                <span>{{ formatDateTime(currentContract.createdAt) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>审核人：</label>
                <span>{{ currentContract.auditBy || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>审核时间：</label>
                <span>{{ formatDateTime(currentContract.auditTime) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 审核信息 -->
        <el-card v-if="currentContract.auditRemark" class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">审核信息</span>
          </template>
          <div class="info-item">
            <label>审核备注：</label>
            <span>{{ currentContract.auditRemark }}</span>
          </div>
        </el-card>

        <!-- 物料明细表 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">物料明细</span>
          </template>
          <div v-if="currentContract.quotation?.items && currentContract.quotation.items.length > 0">
            <el-table :data="currentContract.quotation.items" border stripe>
              <el-table-column prop="itemNo" label="序号" width="60" align="center" />
              <el-table-column prop="productName" label="产品名称" width="120" />
              <el-table-column prop="materialCode" label="物料编码" width="100" />
              <el-table-column prop="layers" label="层数" width="60" align="center" />
              <el-table-column prop="thickness" label="板厚(mm)" width="80" align="center" />
              <el-table-column prop="outerCopper" label="外铜" width="60" align="center" />
              <el-table-column prop="innerCopper" label="内铜" width="60" align="center" />
              <el-table-column prop="deliverySize" label="交货尺寸" width="100" />
              <el-table-column prop="panelization" label="拼板" width="80" />
              <el-table-column prop="surfaceTreatment" label="表面处理" width="100" />
              <el-table-column prop="solderMask" label="阻焊" width="80" />
              <el-table-column prop="character" label="字符" width="60" />
              <el-table-column prop="viaProcess" label="过孔工艺" width="100" />
              <el-table-column prop="testing" label="测试" width="80" />
              <el-table-column prop="quantity" label="数量" width="80" align="right" />
              <el-table-column label="单价" width="100" align="right">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.unitPrice) }}
                </template>
              </el-table-column>
              <el-table-column label="测试架费" width="100" align="right">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.testingFee) }}
                </template>
              </el-table-column>
              <el-table-column label="样板费" width="100" align="right">
                <template #default="scope">
                  ¥{{ formatAmount(scope.row.sampleFee) }}
                </template>
              </el-table-column>
              <el-table-column label="合计金额" width="120" align="right">
                <template #default="scope">
                  <span class="amount-text">¥{{ formatAmount(scope.row.totalAmount) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deliveryDate" label="交期" width="100" />
              <el-table-column prop="itemRemark" label="备注" width="150" show-overflow-tooltip />
            </el-table>
          </div>
          <div v-else class="no-content">
            <el-empty description="暂无物料明细" />
          </div>
        </el-card>

        <!-- 合同内容 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">合同内容</span>
          </template>
          <div class="contract-content" v-if="currentContract.contractContent">
            <div v-html="currentContract.contractContent"></div>
          </div>
          <div v-else class="no-content">
            <el-empty description="暂无合同内容" />
          </div>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="canAudit(currentContract)"
            type="warning" 
            @click="handleAudit(currentContract)"
          >
            审核
          </el-button>
          <el-button 
            type="success" 
            @click="handlePreview(currentContract)"
          >
            预览合同
          </el-button>
          <el-button 
            type="primary" 
            @click="handleDownload(currentContract)"
          >
            下载合同PDF
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog 
      v-model="auditDialogVisible" 
      title="合同审核" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="auditForm" ref="auditFormRef" :rules="auditRules" label-width="100px">
        <el-form-item label="合同编号">
          <el-input v-model="auditForm.contractNo" disabled />
        </el-form-item>
        
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="审核通过">审核通过</el-radio>
            <el-radio label="审核拒绝">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核人" prop="auditBy">
          <el-input v-model="auditForm.auditBy" placeholder="请输入审核人姓名" />
        </el-form-item>
        
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input 
            v-model="auditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAudit" :loading="auditLoading">
            确认审核
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合同预览现在使用新窗口打开，不再需要对话框 -->
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Edit, Document, Download, Loading } from '@element-plus/icons-vue'
import { contractAPI } from '../utils/api'

export default {
  name: 'ContractAudit',
  components: {
    Search,
    Refresh,
    View,
    Edit,
    Document,
    Download,
    Loading
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const auditLoading = ref(false)
    const contractList = ref([])
    const selectedContracts = ref([])
    const detailDialogVisible = ref(false)
    const auditDialogVisible = ref(false)
    const pdfDialogVisible = ref(false)
    const currentContract = ref(null)
    const currentPdfContract = ref(null)
    const pdfUrl = ref('')

    // 用户信息
    const userInfo = ref({
      role: localStorage.getItem('userRole') || 'manager',
      employeeName: localStorage.getItem('employeeName') || ''
    })

    // 搜索表单
    const searchForm = reactive({
      contractNo: '',
      status: '',
      customerCode: '',
      customerName: '',
      salesperson: '',
      auditBy: '',
      dateRange: []
    })

    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 审核表单
    const auditForm = reactive({
      contractNo: '',
      status: '',
      auditBy: '',
      auditRemark: ''
    })

    // 审核表单验证规则
    const auditRules = reactive({
      status: [
        { required: true, message: '请选择审核状态', trigger: 'change' }
      ],
      auditBy: [
        { required: true, message: '请输入审核人', trigger: 'blur' }
      ],
      auditRemark: [
        { required: true, message: '请输入审核备注', trigger: 'blur' }
      ]
    })

    // 判断是否可以审核
    const canAudit = (contract) => {
      if (!contract) return false
      
      // 只有待审核状态的合同才能审核
      if (contract.status !== '待审核') return false
      
      // 管理员和业务经理都可以审核
      const userRole = userInfo.value.role
      return userRole === 'admin' || userRole === 'manager'
    }

    // 获取合同列表
    const loadContractList = async () => {
      try {
        loading.value = true
        
        const params = {
          current: pagination.current,
          size: pagination.size,
          contractNo: searchForm.contractNo || undefined,
          status: searchForm.status || undefined,
          customerCode: searchForm.customerCode || undefined,
          customerName: searchForm.customerName || undefined,
          salesperson: searchForm.salesperson || undefined,
          auditBy: searchForm.auditBy || undefined
        }

        // 处理日期范围
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.startDate = searchForm.dateRange[0]
          params.endDate = searchForm.dateRange[1]
        }

        const response = await contractAPI.getContractPage(params)
        
        if (response.code === 200) {
          contractList.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取合同列表失败')
        }
      } catch (error) {
        console.error('获取合同列表失败:', error)
        ElMessage.error('获取合同列表失败')
      } finally {
        loading.value = false
      }
    }

    // 查看详情
    const handleViewDetail = async (row) => {
      try {
        const response = await contractAPI.getContractById(row.id)
        if (response.code === 200) {
          currentContract.value = response.data
          detailDialogVisible.value = true
        } else {
          ElMessage.error(response.message || '获取合同详情失败')
        }
      } catch (error) {
        console.error('获取合同详情失败:', error)
        ElMessage.error('获取合同详情失败')
      }
    }

    // 审核合同
    const handleAudit = (row) => {
      // 检查权限
      if (!canAudit(row)) {
        ElMessage.error('您没有权限审核此合同')
        return
      }

      Object.assign(auditForm, {
        contractNo: row.contractNo,
        status: '',
        auditBy: userInfo.value.employeeName,
        auditRemark: ''
      })
      currentContract.value = row
      auditDialogVisible.value = true
    }

    // 提交审核
    const handleSubmitAudit = async () => {
      try {
        // 表单验证
        if (!auditForm.status || !auditForm.auditBy || !auditForm.auditRemark) {
          ElMessage.error('请填写完整的审核信息')
          return
        }

        auditLoading.value = true
        
        const response = await contractAPI.auditContract(currentContract.value.id, {
          status: auditForm.status,
          auditBy: auditForm.auditBy,
          auditRemark: auditForm.auditRemark
        })

        if (response.code === 200) {
          ElMessage.success('合同审核成功')
          auditDialogVisible.value = false
          detailDialogVisible.value = false
          loadContractList()
        } else {
          ElMessage.error(response.message || '合同审核失败')
        }
      } catch (error) {
        console.error('合同审核失败:', error)
        ElMessage.error('合同审核失败')
      } finally {
        auditLoading.value = false
      }
    }

    // 预览合同
    const handlePreview = async (row) => {
      try {
        const response = await contractAPI.previewContractHtml(row.id)
        
        // 创建新窗口显示HTML内容
        const newWindow = window.open('', '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes')
        if (newWindow) {
          newWindow.document.write(response)
          newWindow.document.close()
          newWindow.document.title = `合同预览 - ${row.contractNo}`
        } else {
          ElMessage.error('无法打开预览窗口，请检查浏览器弹窗设置')
        }
      } catch (error) {
        console.error('预览合同失败:', error)
        ElMessage.error('预览合同失败')
      }
    }

    // 下载合同
    const handleDownload = async (row) => {
      try {
        const response = await contractAPI.downloadContractPdf(row.id)
        
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/pdf' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `合同_${row.contractNo}.pdf`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        ElMessage.success('合同下载成功')
      } catch (error) {
        console.error('下载合同失败:', error)
        ElMessage.error('下载合同失败')
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadContractList()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        contractNo: '',
        status: '',
        customerCode: '',
        customerName: '',
        salesperson: '',
        auditBy: '',
        dateRange: []
      })
      pagination.current = 1
      loadContractList()
    }

    // 刷新
    const handleRefresh = () => {
      loadContractList()
    }

    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedContracts.value = selection
    }

    // 页码变化
    const handleCurrentChange = (page) => {
      pagination.current = page
      loadContractList()
    }

    // 页大小变化
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      loadContractList()
    }

    // 格式化金额
    const formatAmount = (amount) => {
      if (!amount) return '0.00'
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        '待审核': 'warning',
        '审核通过': 'success',
        '审核拒绝': 'danger'
      }
      return statusMap[status] || 'info'
    }

    // 组件挂载时加载数据
    onMounted(() => {
      // 获取用户信息
      const token = localStorage.getItem('token')
      if (token) {
        try {
          // 解析JWT token获取用户信息
          const payload = JSON.parse(atob(token.split('.')[1]))
          userInfo.value = {
            role: payload.role || 'manager',
            employeeName: payload.employeeName || ''
          }
        } catch (error) {
          console.error('解析token失败:', error)
        }
      }
      
      loadContractList()
    })

    return {
      // 响应式数据
      loading,
      auditLoading,
      contractList,
      selectedContracts,
      detailDialogVisible,
      auditDialogVisible,
      pdfDialogVisible,
      currentContract,
      currentPdfContract,
      pdfUrl,
      searchForm,
      pagination,
      auditForm,
      auditRules,
      userInfo,

      // 方法
      canAudit,
      loadContractList,
      handleViewDetail,
      handleAudit,
      handleSubmitAudit,
      handlePreview,
      handleDownload,
      handleSearch,
      handleReset,
      handleRefresh,
      handleSelectionChange,
      handleCurrentChange,
      handleSizeChange,
      formatAmount,
      formatDateTime,
      getStatusTagType,

      // 图标
      Search,
      Refresh,
      View,
      Edit,
      Document,
      Download
    }
  }
}
</script>

<style scoped>
.contract-audit {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.contract-table {
  margin-bottom: 20px;
}

.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.contract-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-weight: bold;
  color: #303133;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.contract-content {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

.no-content {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.pdf-dialog {
  display: flex;
  flex-direction: column;
}

.pdf-container {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pdf-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contract-audit {
    padding: 10px;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .contract-table .el-table__body-wrapper {
    overflow-x: auto;
  }
}
</style> 